package cn.vinann.demo.config;

import java.lang.reflect.Method;

import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration.FreeMarkerWebConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImplExporter;

/**
 * 项目配置
 * @author wn
 *
 */
@Configuration
public class DemoConfiguration {

	@Bean
	public DemoErrorAttributes errorAttributes(){
		return new DemoErrorAttributes();
	}
	
	@Bean
	public DemoCommandLineRunner commandLineRunner(){
		return new DemoCommandLineRunner();
	}
	
	@Bean
	public FreeMarkerWebConfiguration freeMarkerConfigurer(){
		return new FreeMarkerWebConfiguration();
	}
	
	/**
     * 设置缓存对象的序列化方式及缓存时间
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(300);
        return cacheManager;
    }

    /**
     * 缓存自定义key的生成策略
     * @return
     */
    @Bean
    public KeyGenerator myKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(String.valueOf(obj));
                }
                return sb.toString();
            }
        };
    }
    //跨域
    /*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/promotion/**");//.allowedOrigins("http://tweb.test.akcomejf.com:808");
    }*/
    
    @Bean
    public AutoJsonRpcServiceImplExporter autoJsonRpcServiceImplExporter(){
    	return new AutoJsonRpcServiceImplExporter();
    }
}
